﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Xml.Linq;
using CookComputing.XmlRpc;
//
using PerceptiveMCAPI.Types.Internal;
//
namespace PerceptiveMCAPI.Types
{
	public class listMemberActivityOutput : Api_BaseOutput
	{
		public listMemberActivityResults result { get; set; }
		public listMemberActivityParms inputParms { get; private set; }
		//
		public listMemberActivityOutput( listMemberActivityInput input )
			: base( input )
		{
			inputParms = input.parms;
			result = new listMemberActivityResults();
		}
		// --------------------------------------------------- tostring
		public override string ToString()
		{
			return "ToString() not yet implemented";
		}

		#region ================================================================== format setup
		// ---- serial
		internal void Format( string api_Request, string api_Response )
		{
			this.api_Request = api_Request;
			this.api_Response = api_Response;
			// ----------------------------------
			if ( this.api_OutputType == EnumValues.OutputType.JSON )
				outputJSON();
			else if ( this.api_OutputType == EnumValues.OutputType.XML )
				outputXML();
		}
		// ---- xmlrpc
		internal void Format( XmlRpcStruct rpcResult )
		{
			this.api_Request = EnumValues.NotSupplied;
			this.api_Response = EnumValues.NotSupplied;
			// ------------------------
			this.result = FormatResults( rpcResult );
		}
		#endregion

		#region  ===================================================================== format result
		// ---------------------------------------------------------- outputXML
		protected void outputXML()
		{
			XElement xml = XElement.Parse( this.api_Response );
			// error check
			Api_Error error = apiSerial.GetXmlOutputError( xml );
			if ( error != null )
			{
				this.api_ErrorMessages.Add( error );
				return;
			}
			// -------------------------------------------- get values

			try
			{
				listMemberActivityResults results = new listMemberActivityResults();
				DateTime dt; int it; int ix = -1;
				//
				int.TryParse( xml.Element( "success" ).Value, out it );
				results.success = it;
				int.TryParse( xml.Element( "errors" ).Value, out it );
				results.errors = it;
				//
				IEnumerable<XElement> data = xml.Element( "data" ).Elements( "struct" );
				foreach ( XElement entry in data )
				{
					ix++;
					string email_address = inputParms.email_address[ix];
					IEnumerable<XElement> entry_list = entry.Elements( "struct" );
					foreach ( XElement item in entry_list )
					{
						listMemberActivityResults.activity act = new listMemberActivityResults.activity();
						act.email_address = email_address;
						act.action = item.Element( "action" ).Value;
						DateTime.TryParse( item.Element( "timestamp" ).Value, out dt );
						act.timestamp = dt;
						act.url = item.Element( "url" ).Value ?? "";
						act.bounce_type = item.Element( "bounce_type" ).Value ?? "";
						act.campaign_id = item.Element( "campaign_id" ).Value ?? "";
						//
						results.data.Add( act );
					}
				}
				this.result = results;
			}
			catch ( Exception ex )
			{
				this.api_ErrorMessages.Add( apiException.FormatError( ex ) );
			}
		}
		// ---------------------------------------------------------- outputJSON
		protected void outputJSON()
		{
			JavaScriptSerializer jss = new JavaScriptSerializer();

			try
			{
				if ( this.api_Response.Contains( EnumValues.JSONErrorString ) )
				{
					Api_Error err = jss.Deserialize<Api_Error>( this.api_Response );
					this.api_ErrorMessages.Add( err );
				}
				else
				{
					IDictionary jsonResult = jss.Deserialize<IDictionary>( this.api_Response );
					this.result = FormatResults( jsonResult );
				}
			}
			catch ( Exception ex )
			{
				this.api_ErrorMessages.Add( apiException.FormatError( ex ) );
			}
		}
		// -----------------------------------------------------
		protected listMemberActivityResults FormatResults( IDictionary x_results )
		{
			int it; DateTime dt;
			var results = new listMemberActivityResults();
			// -------------------------------------------------------- success
			if ( x_results["success"] == null )
				results.success = 0;
			else
			{
				int.TryParse( x_results["success"].ToString(), out it );
				results.success = it;
			}
			// -------------------------------------------------------- errors
			if ( x_results["errors"] == null )
				results.errors = 0;
			else
			{
				int.TryParse( x_results["errors"].ToString(), out it );
				results.errors = it;
			}
			// -------------------------------------------------------- data
			int ix = -1;
			object[] email_obj = x_results["data"] as object[];
			foreach ( object[] email in email_obj )
			{
				ix++;
				string email_address = inputParms.email_address[ix];
				// get actions
				foreach ( object act_obj in email )
				{
					listMemberActivityResults.activity activity = new listMemberActivityResults.activity();
					IDictionary item = act_obj as IDictionary;
					//
					activity.email_address = email_address;
					activity.action = item["action"].ToString();
					DateTime.TryParse( item["timestamp"].ToString(), out dt );
					activity.timestamp = dt;
					if ( item["url"] == null )
						activity.url = "";
					else
						activity.url = item["url"].ToString();
					//
					if ( item["bounce_type"] == null )
						activity.bounce_type = "";
					else
						activity.bounce_type = item["bounce_type"].ToString();
					//
					if ( item["campaign_id"] == null )
						activity.campaign_id = "";
					else
						activity.campaign_id = item["campaign_id"].ToString();
					//
					results.data.Add( activity );
				}
			}
			//------------------- 
			return results;
		}
		//
		#endregion
	}
}
